import { Component, ViewEncapsulation, ChangeDetectionStrategy, ElementRef, ChangeDetectorRef } from '@angular/core';
import { Subject } from 'rxjs';
import { LvConfig, TypeUtils } from '../core/api';
import { MessageContainerService } from './message.container.service';

@Component({
  selector: 'lv-message-container',
  exportAs: 'lvMessageContainer',
  templateUrl: './message.container.component.html',
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    '[class.lv-message-queue-container]': 'true',
  },
})
export class MessageContainerComponent {
  public messagePos = '';

  private typeUtils = TypeUtils;

  constructor(
    public cdr: ChangeDetectorRef,
    public el: ElementRef,
    public messageContainer: MessageContainerService,
  ) {}

  remove(tag, id): void {
    this.messageContainer.remove(this.cdr, tag, id);
    this.cdr.detectChanges();
  }

  removeAll(): void {
    this.messageContainer.messages = {
      topLeft: [],
      topCenter: [],
      topRight: [],
    };
    this.cdr.detectChanges();
  }

  update(tag, options): void {
    const messages = this.messageContainer.messages[tag];
    messages.forEach((item): void => {
      if (item.id === options.id) {
        if (this.typeUtils.isNotNil(options.isSimple)) {
          item.isSimple = options.isSimple;
        }
        item.options = { ...item.options, ...options.options };
        item.change$.next();
      }
    });

    this.cdr.markForCheck();
  }

  create(options): void {
    this.messagePos = options.options.lvPosition;
    const messages = this.messageContainer.messages[options.options.lvPosition];
    const isExist = messages.some((item): boolean => item.id === options.id);
    if (isExist) {
      return;
    }

    // 添加一个Observer, 用于子组件观察update方法
    options.change$ = new Subject<any>();

    if (messages.length > LvConfig.messageOptions.lvMaxStacks - 1) {
      messages.pop();
    }
    messages.unshift(options);
    this.cdr.markForCheck();
  }
}
